package com.shanghaionstar.mro;

import android.animation.AnimatorInflater;
import android.animation.AnimatorSet;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.PreferencesUtls;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.utils.RxBus;
import com.onstar.cn.framework.utils.RxSubscriptions;
import com.onstar.cn.mag.enumtype.RemoteCommandsType;
import com.onstar.cn.map.common.PoiItemInfo;
import com.onstar.cn.rxconstants.RxConstants;
import com.onstar.cn.vehicle.entity.ErrorInfo;
import com.onstar.cn.vehicle.entity.RequestStatus;
import com.onstar.cn.vehicle.result.PollingResult;
import com.onstar.cn.weight.ToastView;
import com.shanghaionstar.R;
import com.shanghaionstar.activity.VehicleLoadingActivity;
import com.shanghaionstar.enumtype.Event;
import com.shanghaionstar.mro.adapter.MrOPoiListAdapter;
import com.shanghaionstar.mro.iview.IMroPoiView;
import com.shanghaionstar.mro.presenter.MroPoiPresenter;
import com.shanghaionstar.remote.model.RemoteModel;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.utils.OperateB2CUtil;

import java.util.List;

import rx.Subscription;
import rx.functions.Action1;

import static com.onstar.cn.mag.enumtype.RemoteCommandsType.COMMANDS_NAV_DESTINATION;
import static com.onstar.cn.mag.enumtype.RemoteCommandsType.COMMANDS_TBT_ROUTE;

public class MrOPoiFragment extends MrOBaseFragment implements IMroPoiView {
    private View view;
    private List<PoiItemInfo> searchResultList;
    private MrOActivity mroActivity;
    @FindViewById
    private ListView poilist;
    private MrOPoiListAdapter mrOPoiListAdapter;
    //    private MrOPoiUtil poiUtil;
    @FindViewById
    private TextView tv_poi_text;
    private static final String KEY_PLACE = "KEY_PLACE";
    private String keyPlace;
    private String hintWords;
    @FindViewById
    private FrameLayout tbt_progress;

    private MroPoiPresenter presenter;

    private Handler resultHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case Constants.ERROR:
                    tbt_progress.setVisibility(View.GONE);
                    try {
                        RemoteCommandsType commandType = (RemoteCommandsType) msg.getData().getSerializable("commandType");
//                        BusinessUtil.operateReport(getActivity(), commandType,
//                                OperateType.FAILURE, System.currentTimeMillis() + "");
                    } catch (Exception e) {
                        //report failure
                    }
                    ErrorInfo errorInfo = (ErrorInfo) msg.getData().getSerializable("errorInfo");
                    String message = getActivity().getString(R.string.send_to_tbt_failed);
                    tv_poi_text.setText(message);
                    if (errorInfo != null) {
                        OperateB2CUtil.operateEventReport(Event.Connect, errorInfo.getCode() + "," + errorInfo.getMsg(),
                                getActivity(), "2");
                    }
                    break;
                case Constants.SUCCESS:
                    String commandType = (String) msg.obj;
                    if (!CommonUtil.isNull(commandType)) {
                        if (commandType.equals(COMMANDS_TBT_ROUTE.value()) || commandType.equals(COMMANDS_NAV_DESTINATION.value())) {
                            // AlertDialogUtil.showAlertDialog(mroActivity,
                            // mroActivity.getString(R.string.poi_destination_title_str),
                            // mroActivity.getString(R.string.send_to_tbt_progress));
                            tbt_progress.setVisibility(View.GONE);
                            tv_poi_text.setText(mroActivity.getString(R.string.send_to_tbt_progress));
                            // mroActivity.focus(mroActivity.getString(R.string.send_to_tbt_progress));
                        }
                    }
                    break;
                case Constants.SHOW_TBT_PROGRESS:
                    tbt_progress.setVisibility(View.VISIBLE);
                    break;
            }
        }
    };

    private Subscription mPollingRx;

    public void registAllPageAlert() {
//        mPollingRx = RxBus.getDefault().toObserverable(Message.class)
//                .subscribeOn(getScheduler().backgroundThread())
//                .observeOn(getScheduler().mainThread()).subscribe(new Action1<Message>() {
//                    @Override
//                    public void call(Message msg) {
//                        switch (msg.what) {
//                            case RxConstants.REMOTE_ERROR:
//                                ErrorInfo errorInfo = (ErrorInfo) msg.obj;
//                                AlertDialogUtil.showAlertDialog(MrOActivity.this, getString(R.string.dialog_warning), errorInfo.getDescription());
//                                break;
//                            case RxConstants.REMOTE_POLLING:
//                                RemoteModel model = (RemoteModel) msg.obj;
//                                presenter.saveHis(model);
//                                break;
//                            case RxConstants.REMOTE_WITHOUT_PING:
//                                RemoteModel model1 = (RemoteModel) msg.obj;
//                                presenter.onAutoSendPin(model1);
//                                break;
//                            case RxConstants.REMOTE_POLLING_RESULT:
//                                PollingResult pollingResult = (PollingResult) msg.obj;
//                                RemoteCommandsType remotecommandType = RemoteCommandsType.fromValue(pollingResult.getRequestType());
//                                if (pollingResult != null) {
//                                    if (pollingResult.getRequestType().equals(RemoteCommandsType.COMMANDS_TBT_ROUTE.value())) {
//                                        if (pollingResult.getRequestStatus().equals(RequestStatus.Success.getStringValue())) {
//                                            AlertDialogUtil.showAlertDialog(MrOActivity.this, getString(R.string.dialog_warning), getString(R.string.send_to_tbt_success));
//                                        } else if (pollingResult.getRequestStatus().equals(RequestStatus.Failure.getStringValue())) {
//                                            AlertDialogUtil.showAlertDialog(MrOActivity.this, getString(R.string.dialog_warning), getString(R.string.send_to_tbt_failed));
//                                        }
//                                    } else if (presenter.isRemoteCommand(pollingResult.getRequestType())) {
//                                        if (RequestStatus.Success.getStringValue().equalsIgnoreCase(pollingResult.getRequestStatus())) {
//                                            sendRemoteReport(OperateReportUtil.CONTENT_SUCCESS);
//                                            presenter.updateView(pollingResult);
//                                        } else if (RequestStatus.Failure.getStringValue().equalsIgnoreCase(pollingResult.getRequestStatus())) {
//                                            sendRemoteReport(OperateReportUtil.CONTENT_FAIL);
//                                            presenter.updateView(pollingResult);
//                                        }
//                                    }
//                                }
//                                break;
//                        }
//
//
//                    }
//                });
//        RxSubscriptions.add(mPollingRx);


        mPollingRx = RxBus.getDefault().toObserverable(Message.class)
                .subscribeOn(mroActivity.getScheduler().backgroundThread())
                .observeOn(mroActivity.getScheduler().mainThread()).subscribe(new Action1<Message>() {
                    @Override
                    public void call(Message msg) {
                        if (mroActivity == null)
                            return;
                        switch (msg.what) {
                            case RxConstants.REMOTE_ERROR:
                                ErrorInfo errorInfo = (ErrorInfo) msg.obj;
                                AlertDialogUtil.showAlertDialog(getActivity(), getString(R.string.dialog_warning), errorInfo.getDescription());
                                break;
                            case RxConstants.REMOTE_POLLING:
                                RemoteModel model = (RemoteModel) msg.obj;
                                presenter.saveHis(model);
                                break;
                            case RxConstants.REMOTE_POLLING_RESULT:
                                PollingResult pollingResult = (PollingResult) msg.obj;
                                handlePollingResult(pollingResult);
                                break;
                        }
                    }
                });
        RxSubscriptions.add(mPollingRx);
    }

    private void handlePollingResult(PollingResult pollingResult) {
        RemoteCommandsType
                remotecommandType = RemoteCommandsType.fromValue(pollingResult.getRequestType());
        if (remotecommandType == null) return;
        switch (remotecommandType) {
            case COMMANDS_TBT_ROUTE: //tbt or odd
            case COMMANDS_NAV_DESTINATION:
                if (pollingResult.getRequestStatus().equals(RequestStatus.Success.getStringValue())) {
                    tbt_progress.setVisibility(View.GONE);
                    tv_poi_text.setText(mroActivity.getString(R.string.send_to_tbt_progress));
                } else {
                    tbt_progress.setVisibility(View.GONE);
                    try {
//                                RemoteCommandsType commandType = (RemoteCommandsType) msg.getData().getSerializable("commandType");
//                                BusinessUtil.operateReport(getActivity(), remotecommandType,
//                                        OperateType.FAILURE, System.currentTimeMillis() + "");
                    } catch (Exception e) {
                        //report failure
                    }
                    ErrorInfo errorInfo = pollingResult.getErrorInfo();
                    String message = getActivity().getString(R.string.send_to_tbt_failed);
                    tv_poi_text.setText(message);
                    if (errorInfo != null) {
                        OperateB2CUtil.operateEventReport(Event.Connect, errorInfo.getCode() + "," + errorInfo.getMsg(),
                                getActivity(), "2");
                    }
                }
                break;

        }
    }


    public static MrOPoiFragment newInstance(String keyPlace) {
        MrOPoiFragment fragment = new MrOPoiFragment();
        Bundle args = new Bundle();
        args.putString(KEY_PLACE, keyPlace);
        fragment.setArguments(args);
        return fragment;
    }

    public MrOPoiFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            keyPlace = getArguments().getString(KEY_PLACE);
        }
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.mro_poi, container, false);
            injectView(view);
        } else {
            super.onResumeView(view);
        }

        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
        tv_poi_text.setText(hintWords);
        mroActivity = (MrOActivity) getActivity();
        presenter = new MroPoiPresenter(mroActivity.getScheduler());
        presenter.setView(this);

//        poiUtil = MrOPoiUtil.getInstance();
//                .refreshActivity(mroActivity);
        mrOPoiListAdapter = new MrOPoiListAdapter(mroActivity, searchResultList);
        mrOPoiListAdapter.setSendToCarListen(sendToCarListener);
        poilist.setAdapter(mrOPoiListAdapter);
    }

    public void setSearchResultList(List<PoiItemInfo> searchResultList) {
        this.searchResultList = searchResultList;
    }

    public void setHintWords(String words) {
        this.hintWords = words;
    }

    private View.OnClickListener sendToCarListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
//          mroActivity.circle();
            registAllPageAlert();
            if (PreferencesUtls.getInstance(mroActivity).getBoolean(
                    FinalConstants.SharedPreferencesConfig.TBT_CHOOSE_SAVE, true)) {
                presenter.sendTbtOrOdd(searchResultList.get((Integer) v.getTag()));
//                poiUtil.sendToTBT(searchResultList.get((Integer) v.getTag()), resultHandler);
            } else if (PreferencesUtls.getInstance(mroActivity).getBoolean(
                    FinalConstants.SharedPreferencesConfig.ODD_CHOOSE_SAVE, false)) {
                presenter.sendTbtOrOdd(searchResultList.get((Integer) v.getTag()));
//                poiUtil.sendToODD(searchResultList.get((Integer) v.getTag()), resultHandler);
            }
//            mroActivity
//                    .changeFragment(mroActivity.fragmentManager, new MrOHomeFragment(), MrOHomeFragment.class, true);
        }
    };


    public void updateView(PollingResult result) {
        if (!CommonUtil.isNull(result)) {
            poilist.setVisibility(View.GONE);
            if (result.getRequestStatus().equals(RequestStatus.Success.getStringValue())) {
                tv_poi_text.setText(mroActivity.getString(R.string.send_to_tbt_success));
            } else if (result.getRequestStatus().equals(RequestStatus.Failure.getStringValue())) {
                tv_poi_text.setText(mroActivity.getString(R.string.send_to_tbt_failed));
            }
            if (Build.VERSION.SDK_INT >= 11) {
                AnimatorSet animatorSet = (AnimatorSet) AnimatorInflater.loadAnimator(mroActivity, R.animator.mro_replymsg_show);
                animatorSet.setTarget(tv_poi_text);
                animatorSet.start();
            }
        }
    }

    @Override
    public void showCommandLoading(boolean loading) {
        if (loading) {
            if (getActivity() != null)
                startActivity(new Intent(getActivity(), VehicleLoadingActivity.class));
        }
//        tbt_progress.setVisibility(View.VISIBLE)
    }

    @Override
    public void showAppFrontNavCommandFailToast(final PoiItemInfo poiItemInfo) {
        AlertDialogUtil.showAlertDialog(mroActivity, getString(R.string.dialog_warning), getString(R.string.nav_command_fail_alert), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                presenter.sendTbtOrOdd(poiItemInfo);
            }
        });
    }

    @Override
    public void showAppBackNavCommandFailToast(final PoiItemInfo poiItemInfo) {
        ToastView toastView = new ToastView(mroActivity);
        toastView.setToastClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAppFrontNavCommandFailToast(poiItemInfo);
            }
        });
    }

    @Override
    public void setLoading(boolean isLoading) {

    }

    @Override
    public void onResponseError(OnStarException e) {

    }

    @Override
    public void onReponseSuccess(Object object) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxSubscriptions.remove(mPollingRx);
    }

    @Override
    public Activity onActivity() {
        return getActivity();
    }
}
